import axios from 'axios'
import { createStore, Commit } from 'vuex'

const asyncAndCommit = async (url: string, mutationName: string, commit: Commit, config: any = { method: 'get' }) => {
    const { data } = await axios(url, config)
    commit(mutationName, data)
    return data
}
export interface ResponseType<p = unknown> {
    code: number;
    msg: string;
    data: p;
}
export interface GlobalErrorProps {
    status: boolean;
    message?: string;
}
export interface ImageProps {
    _id?: string;
    url?: string;
    createdAt?: string;
    fitUrl?: string;
}
export interface ColumnProps {
    _id: string;
    title: string;
    avatar?: ImageProps;
    description: string;
}

export interface userProps {
    isLogin: boolean
    nickName?: string
    _id?: string,
    email?: string,
    column?: string,
    description?: string,
    avatar?: ImageProps
}
export interface PostProps {
    _id?: string;
    title: string;
    excerpt?: string;
    content: string;
    image?: ImageProps | string;
    createdAt?: string;
    column: string;
    author?: string | userProps;
    isHTML?: boolean;
}
export interface GlobalDataProps {
    error: GlobalErrorProps,
    token: string,
    loading: boolean,
    columns: ColumnProps[],
    posts: PostProps[],
    user: userProps
}
const store = createStore<GlobalDataProps>({
    state: {
        error: { status: false },
        token: localStorage.getItem('token') || '',
        loading: false,
        columns: [],
        posts: [],
        user: { isLogin: false }
    },
    mutations: {
        // login(state) {
        //     state.user = { isLogin: true, name: 'shanyoufuzhu' }
        // },
        createPost(state, newPost) {
            state.posts.push(newPost)
        },
        // 获取首页展示的columns
        fetchColumns(state, rawData) {
            state.columns = rawData.data.list
        },
        // 获取单个column详情
        fetchColumn(state, rawData) {
            state.columns = [rawData.data]
        },
        // 获取专栏详情中的文章列表
        fetchPosts(state, rawData) {
            state.posts = rawData.data.list
        },
        // 获取单篇文章信息
        fetchPost(state, rawData) {
            state.posts = [rawData.data]
        },
        deletePost(state, { data }) {
            state.posts = state.posts.filter(post => post._id !== data._id)
        },
        updatePost(state, { data }) {
            state.posts = state.posts.map(post => {
                if (post._id === data._id) {
                    return data
                } else {
                    return post
                }
            })
        },
        setLoading(state, status) {
            state.loading = status
        },
        setError(state, e: GlobalErrorProps) {
            state.error = e
        },
        login(state, rawData) {
            const { token } = rawData.data
            state.token = token
            localStorage.setItem('token', token)
            axios.defaults.headers.common.Authorization = `Bearer ${token}`
        },
        logout(state) {
            state.token = ''
            state.user = { isLogin: false }
            localStorage.removeItem('token')
            delete axios.defaults.headers.common.Authorization
        },
        fetchCurrentUser(state, rawData) {
            state.user = { isLogin: true, ...rawData.data }
        }
    },
    actions: {
        fetchColumns({ commit }) {
            return asyncAndCommit('/columns', 'fetchColumns', commit)
        },
        fetchColumn({ commit }, cid) {
            return asyncAndCommit(`/columns/${cid}`, 'fetchColumn', commit)
        },
        fetchPosts({ commit }, cid) {
            return asyncAndCommit(`/columns/${cid}/posts`, 'fetchPosts', commit)
        },
        fetchPost({ commit }, id) {
            return asyncAndCommit(`/posts/${id}`, 'fetchPost', commit)
        },
        deletePost({ commit }, id) {
            return asyncAndCommit(`/posts/${id}`, 'deletePost', commit, { method: 'delete' })
        },
        updatePost({ commit }, { id, payload }) {
            return asyncAndCommit(`/posts/${id}`, 'updatePost', commit, {
                method: 'patch',
                data: payload
            })
        },
        login({ commit }, payload) {
            return asyncAndCommit('/user/login', 'login', commit, { method: 'post', data: payload })
        },
        createPost({ commit }, payload) {
            return asyncAndCommit('/posts', 'createPost', commit, { method: 'post', data: payload })
        },
        fetchCurrentUser({ commit }) {
            return asyncAndCommit('/user/current', 'fetchCurrentUser', commit)
        },
        loginAndFetch({ dispatch }, loginData) {
            return dispatch('login', loginData).then(() => {
                return dispatch('fetchCurrentUser')
            })
        }
    },
    getters: {
        getColumnById: (state) => (id: string) => {
            return state.columns.find(c => c._id === id)
        },
        getPostById: (state) => (cid: string) => {
            return state.posts.filter(post => post.column === cid)
        },
        getCurrentPost: (state) => (id: string) => {
            return state.posts.find(post => post._id === id)
        }
    }
})
export default store
